package com.gshrms.common.utils.file;

import com.gshrms.common.utils.StringUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipsUtils {

    /**
     * 写入文件列表到ZIP输出流
     * @param filePaths
     * @param fileNames
     * @param zipOutputStream
     * @throws IOException
     */
    public static void writeFilesToZipOutputStream(List<String> filePaths, List<String> fileNames, ZipOutputStream zipOutputStream) throws IOException {
        byte[] buffer = new byte[8192];

        for (int i = 0; i < filePaths.size(); i++) {
            String filePath = filePaths.get(i);
            String fileName = fileNames.get(i);
            // 添加原文件名后缀
            String extension = FilenameUtils.getExtension(filePath);
            if (!StringUtils.isEmpty(extension)) fileName += "." + extension;

            File file = new File(filePath);
            if (!file.exists() || file.isDirectory()) {
                // 如果文件不存在或是目录，跳过
                continue;
            }

            // 读取文件并添加到 ZIP
            try (FileInputStream fis = new FileInputStream(file)) {
                ZipEntry entry = new ZipEntry(fileName);
                zipOutputStream.putNextEntry(entry);

                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, length);
                }

                zipOutputStream.closeEntry();
            }
        }
    }
}
